import requests
from lxml import etree
import os

#
data=[]
keyword=input("请输入你想吃的菜:")
headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"}


#实现自动翻页
for j in range(3):
    url=f"https://www.xiachufang.com/search/?keyword={keyword}&page={j}"
    response=requests.get(url=url,headers=headers)
    html=response.text



    selector=etree.HTML(html)

    lst = selector.xpath('/html/body/div[4]/div/div/div[1]/div[1]/div/div[2]/div[1]/ul/li')
    for i in lst:
        name = i.xpath("./div/div/p[1]/a/text()")[0].strip()
        materials = "".join(i.xpath("./div/div/p[2]//text()")[1:-1]).strip()
        url_1 = url + i.xpath("./div/div/p[4]/a/@href")[0]
        recipe_info = f"菜名：{name}\n材料：{materials}\n步骤链接：{url_1}"


        folder_path="D:\\code\pythonProject1\\database\\食谱"
        file_path=os.path.join(folder_path,f"{name}.txt")
        with open(file_path,"w",encoding="utf-8") as file:
            file.write(recipe_info)
            file.close()




